/************************************************************************************************
 * test examples of 100 interesting program in C
 * test 010.c
 * print binary representation of decimal number
 ***********************************************************************************************/

#include <stdio.h>

/*
 * this solution is much simpler than great-division, which can only deal with positive numbers
 * but for non-2-carry representation, great-division is the only way
 */

int printb(int x, int n);

int main()
{
	int x = 0;
	printf("Input number: ");
	scanf("%d", &x);
	printf("Decimal number: %d\n", x);
	printf("--it's binary form is: ");
	printb(x, sizeof(int)*8);
	putchar('\n');
}

int printb(int x, int n)
{
	if (n > 0)
	{
		// this << and >> is to get the nth (right to left) bit's value.
		// for example, the 1st bit on the left is the 32nd on the right, so we need
		// to move 1 left by 31 (n-1) bits left then "&" operation can get its value.
		// "'0' +" is to transform number 0/1 to char '0'/'1'
		putchar('0' + ((unsigned)(x & (1 << (n-1))) >> (n-1)));
		printb(x, n-1);
		return(0);
	}
	else
	{
		return(-1);
	}
}

